package eproject.mm.com.projectsupervision;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;
import com.tencent.android.tpush.common.Constants;

import java.util.ArrayList;
import java.util.Map;

import eproject.mm.com.projectsupervision.activity.CardActivity;
import eproject.mm.com.projectsupervision.activity.LoginActivity;
import eproject.mm.com.projectsupervision.fragment.MainFragment;
import eproject.mm.com.projectsupervision.fragment.MessageFragment;
import eproject.mm.com.projectsupervision.fragment.ProfileFragment;
import eproject.mm.com.projectsupervision.fragment.ProjectFragment;
import eproject.mm.com.projectsupervision.util.HttpUtil;
import eproject.mm.com.projectsupervision.util.TimeUtil;
import eproject.mm.com.projectsupervision.widget.IconFontTextview;

public class MainActivity extends AppCompatActivity {
    private final int SDK_PERMISSION_REQUEST = 127;
    private String permissionInfo;

    private Fragment[] fragments;

    private MainFragment mainFragment;
    private ProjectFragment projectFragment;
    private MessageFragment messageFragment;
    private ProfileFragment profileFragment;

    private ImageView[] imageViews;
    private IconFontTextview[] textTopViews;
    private TextView[] textViews;
    private int index;
    private int curTabInex;

    private long firstTime=0;
    MyTabChangeReceiver receiver;
    RelativeLayout rl_project;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(!PrjApplication.getInstance().isLogin()){
            finish();
            startActivity(new Intent(getApplicationContext(), LoginActivity.class));
        }
        setContentView(R.layout.activity_main);

        initViews();
        getPersimmions();

        receiver = new MyTabChangeReceiver();
        final IntentFilter filter = new IntentFilter();
        filter.addAction(PrjApplication.getInstance().TabChangeAction);
        registerReceiver(receiver, filter);


        XGPushConfig.enableDebug(this, true);

        XGPushManager.registerPush(getApplicationContext(),
                new XGIOperateCallback() {
                    @Override
                    public void onSuccess(final Object data, int flag) {
                        Log.w(Constants.LogTag, "+++ register push sucess. token:" + data + "flag" + flag);
                        PrjApplication.getInstance().setXGToken(data.toString());

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    HttpUtil.get("/refreshXGToken?token=" + data.toString()+"&errcode=");
                                } catch (Exception e) {}
                            }
                        }).start();
                    }

                    @Override
                    public void onFail(Object data, int errCode, String msg) {
                        Log.w(Constants.LogTag,
                                "+++ register push fail. token:" + data
                                        + ", errCode:" + errCode + ",msg:"
                                        + msg);
                        PrjApplication.getInstance().setXGToken("");
                        final String errcode = String.valueOf(errCode);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    HttpUtil.get("/refreshXGToken?token=&errcode=" + String.valueOf(errcode));
                                } catch (Exception e) {}
                            }
                        }).start();
                    }
                });
        // 获取token
        XGPushConfig.getToken(this);
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        unregisterReceiver(receiver);
    }
    private void initViews(){
        mainFragment = new MainFragment();
        projectFragment = new ProjectFragment();
        messageFragment = new MessageFragment();
        profileFragment = new ProfileFragment();

        fragments = new Fragment[]{
                mainFragment, projectFragment, messageFragment, profileFragment
        };

//        imageViews = new ImageView[4];
//        imageViews[0] = (ImageView)findViewById(R.id.iv_project);
//        imageViews[1] = (ImageView)findViewById(R.id.iv_project);
//        imageViews[2] = (ImageView)findViewById(R.id.iv_message);
//        imageViews[3] = (ImageView)findViewById(R.id.iv_profile);
//
//        imageViews[0].setSelected(true);
        rl_project = (RelativeLayout)findViewById(R.id.rl_project);

        textViews = new TextView[4];
        textViews[0] = (TextView)findViewById(R.id.tv_home);
        textViews[1] = (TextView)findViewById(R.id.tv_project);
        textViews[2] = (TextView)findViewById(R.id.tv_message);
        textViews[3] = (TextView)findViewById(R.id.tv_profile);

        textTopViews = new IconFontTextview[4];
        textTopViews[0] = (IconFontTextview)findViewById(R.id.iftv_home);
        textTopViews[1] = (IconFontTextview)findViewById(R.id.iftv_project);
        textTopViews[2] = (IconFontTextview)findViewById(R.id.iftv_message);
        textTopViews[3] = (IconFontTextview)findViewById(R.id.iftv_profile);

        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, mainFragment)
                .add(R.id.fragment_container, projectFragment)
                .add(R.id.fragment_container, messageFragment)
                .add(R.id.fragment_container, profileFragment)
                .hide(profileFragment)
                .hide(messageFragment)
                .hide(projectFragment).show(mainFragment).commit();

        curTabInex = 0;
        textViews[0].setTextColor(ContextCompat.getColor(this,R.color.tabSelectedColor));
        textTopViews[0].setTextColor(ContextCompat.getColor(this,R.color.tabSelectedColor));
    }
    public void onTabClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_home:
                index = 0;
                break;
            case R.id.rl_project:
                index = 1;
                break;
            case R.id.rl_message:
                index = 2;
                break;
            case R.id.rl_profile:
                index = 3;
                break;

        }

        if (curTabInex != index) {
            FragmentTransaction trx = getSupportFragmentManager()
                    .beginTransaction();
            trx.hide(fragments[curTabInex]);
            if (!fragments[index].isAdded()) {
                trx.add(R.id.fragment_container, fragments[index]);
            }
            trx.show(fragments[index]).commit();
        }
        //imageViews[curTabInex].setSelected(false);
        // 把当前tab设为选中状态
        //imageViews[index].setSelected(true);
        textViews[curTabInex].setTextColor(ContextCompat.getColor(this,R.color.tabNormalColor));
        textViews[index].setTextColor(ContextCompat.getColor(this,R.color.tabSelectedColor));
        textTopViews[curTabInex].setTextColor(ContextCompat.getColor(this,R.color.tabNormalColor));
        textTopViews[index].setTextColor(ContextCompat.getColor(this,R.color.tabSelectedColor));

        curTabInex = index;
    }


    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
			/*
			 * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            //获取计步器权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.BODY_SENSORS Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)){
                return true;
            }else{
                permissionsList.add(permission);
                return false;
            }

        }else{
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode){
            case KeyEvent.KEYCODE_BACK:
                long secondTime=System.currentTimeMillis();
                if(secondTime-firstTime>2000){
                    Toast.makeText(MainActivity.this,"再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime=secondTime;
                    return true;
                }else{
                    System.exit(0);
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    public class MyTabChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, final Intent intent) {
            String action = intent.getAction();
            if(action.equals(PrjApplication.getInstance().TabChangeAction)){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        onTabClicked(rl_project);
                    }
                });
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0){
            if(resultCode==101){//上班
                mainFragment.setWorkStatus(1);
            }else if(resultCode==102) {//下班
                mainFragment.setWorkStatus(2);
            }
        }
    }
}
